//https://github.com/javascript-obfuscator/javascript-obfuscator#deadcodeinjection
var JavaScriptObfuscator = require('javascript-obfuscator');
var fs = require("fs");
var path = require("path");
var child_process = require('child_process');

var os = require('os');
var ifaces = os.networkInterfaces();

var ip = null;

Object.keys(ifaces).forEach(function (ifname) {
    var alias = 0;

    ifaces[ifname].forEach(function (iface) {
        if ('IPv4' !== iface.family || iface.internal !== false) {
            // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
            return;
        }

        if (alias >= 1) {
            // this single interface has multiple ipv4 addresses
            console.log(ifname + ':' + alias, iface.address);
        } else {
            // this interface has only one ipv4 adress
            console.log(ifname, iface.address);
            if(ip == null) ip = iface.address;
        }
        ++alias;
    });
});

var publishFolder = "../wechat";
//publishFolder = "../test";

var obscure = false;
if(publishFolder == "../test") obscure = false;

//var sourceFolders = ["res"];
var sourceFolders = [];

//清空创建发布文件夹
try{
    fs.mkdirSync(publishFolder);
} catch (e) {

}

var outJsName = "gameCore.js";

for(var i = 0; i < sourceFolders.length; i++) {
    deleteFolderRecursive(publishFolder + "/" + sourceFolders[i]);
    copyDir("../" + sourceFolders[i], publishFolder + "/" + sourceFolders[i]);
}
try{
    fs.unlinkSync(publishFolder + "/project.json");
} catch(e) {

}
try {
    fs.unlinkSync(publishFolder + "/" + outJsName);
} catch(e) {

}

var projectJson = JSON.parse(fs.readFileSync("../project.json", "utf8"));
//资源地址，TODO
projectJson.resUrl = "http://" + ip + ":8888/";
// projectJson.resUrl = "http://120.24.180.89/h5/hexRes/";
//是否微信小游戏
projectJson.wx = true;
fs.writeFileSync(publishFolder + "/project.json", JSON.stringify(projectJson));

/**
 * @author       Longsir <longames@qq.com>
 * @copyright    2015 Longames Ltd.
 * @github       {@link https://github.com/longyangxi/flax.js}
 * @flax         {@link http://flax.so}
 * @license      MIT License: {@link http:http://mit-license.org/}
 */

var loadJsonSync = function (url, callback) {
    var http = new XMLHttpRequest();
    http.open("GET", url, false);
    if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
        // IE-specific logic here
        http.setRequestHeader("Accept-Charset", "utf-8");
    } else {
        if (http.overrideMimeType) http.overrideMimeType("text\/plain; charset=utf-8");
    }
    http.onreadystatechange = function () {
        if(http.readyState == 4){
            if(http.status == 200){
                var response = http.responseText;
                response = response.replace(/\\/g,"");
                try{
                    response = JSON.parse(response);
                } catch (e) {

                }
                if(callback){
                    callback(response);
                }
            }else{

            }
        }else{
            //cc.log(xhr.status + ", " + xhr.readyState)
        }
    }
    http.send(null);
}

var flaxDir = "../src/flax";
var mainStr = "";
var loadJsList = function (urls, isFlax) {
    for(var i = 0; i< urls.length; i++) {
        var url = flaxDir + "/" + urls[i];
        if(!isFlax) url = "../" + urls[i];
        mainStr += fs.readFileSync(url, "utf8") + "\n";
    }
}

var userConfig = JSON.parse(fs.readFileSync(publishFolder + "/project.json", "utf8"));
var modules = userConfig['modules'];

var moduleConfig = JSON.parse(fs.readFileSync(flaxDir + "/" + "moduleConfig.json", "utf8"));

var engineName = "pixi";
for(var i = 0; i < modules.length; i++) {
    var moduleName = modules[i];
    var module = moduleConfig['modules'][moduleName];
    if(module) {
        if(module['base']) loadJsList(module['base'], true);
        if(module[engineName + "_base"]) loadJsList(module[engineName + "_base"], true);
        if(module['common']) loadJsList(module['common'], true);
        if(module[engineName]) loadJsList(module[engineName], true);
    }
}

loadJsList(userConfig['jsList']);
loadJsList(['main.js']);

//修正pixi的export的问题
mainStr = mainStr.replace(/typeof global !== "undefined" \? global : typeof self !== "undefined" \? self : typeof window !== "undefined" \? window : \{\}/g, 'window');

fs.writeFileSync(publishFolder + "/" + outJsName, mainStr);

//删除文件夹
function deleteFolderRecursive(path) {
    if( fs.existsSync(path) ) {
        fs.readdirSync(path).forEach(function(file) {
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

/*
 * 复制目录、子目录，及其中的文件
 * @param src {String} 要复制的目录
 * @param dist {String} 复制到目标目录
 */
function copyDir(src, dist, callback) {
    fs.access(dist, function(err){
        if(err){
            // 目录不存在时创建目录
            fs.mkdirSync(dist);
        }
        _copy(null, src, dist);
    });

    function _copy(err, src, dist) {
        if(err){
            callback(err);
        } else {
            fs.readdir(src, function(err, paths) {
                if(err){
                    callback(err)
                } else {
                    paths.forEach(function(path) {
                        var _src = src + '/' +path;
                        var _dist = dist + '/' +path;
                        fs.stat(_src, function(err, stat) {
                            if(err){
                                callback(err);
                            } else {
                                // 判断是文件还是目录
                                if(stat.isFile()) {
                                    fs.writeFileSync(_dist, fs.readFileSync(_src));
                                } else if(stat.isDirectory()) {
                                    // 当是目录是，递归复制
                                    copyDir(_src, _dist, callback)
                                }
                            }
                        })
                    })
                }
            })
        }
    }
}